package com.xiebishe.mylibrary.base

import android.app.Application
import android.content.Context
import com.xiebishe.mylibrary.net.header.HeaderIntercepter
import com.xiebishe.mylibrary.net.okhttp.OkHttpClientManager
import com.xiebishe.mylibrary.net.okhttp.TrustAllCerts
import com.xiebishe.mylibrary.net.retrofit.fastjsonConverter.FastJsonResponseBodyDecodeConverter
import okio.Buffer
import java.lang.reflect.Type
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager


open class MyApplication:Application() {
    var isDebug=true
    var host:String=""//请求主机地址
    var baseManagerApplication=BaseManagerApplication()
    override fun onCreate() {
        super.onCreate()
        baseManagerApplication.onCreate(this)
        baseManagerApplication.onApplicationCreated(this)
        myApplication=this
        context=this
        OkHttpClientManager.setUserInterceptors(HeaderIntercepter(setHttpHead()))

    }

    /**
     * SSL验证
     *
     * @return
     */
     open fun createSSLSocketFactory(): SSLSocketFactory? {
        var ssfFactory: SSLSocketFactory? = null
        try {
            val sc = SSLContext.getInstance("TLS")
            sc.init(null, arrayOf<TrustManager>(TrustAllCerts()), SecureRandom())
            ssfFactory = sc.socketFactory
        } catch (e: Exception) {
        }
        return ssfFactory
    }
    /**
     * 设置请求公共参数
     */
    open fun setHttpHead():MutableMap<String,String>{
        return mutableMapOf()
    }

    /**
     * 加密请求body
     */
    open fun encryptionRequest(buffer: Buffer):Buffer?{
        return null
    }

    /**
     * url加密验证码
     */
    open fun urlVerify(content:String):String{
        return ""
    }
    /**
     * 是否需要返回内容解密
     */
    open fun getDecryptFastJsonResponseBody(type: Type): FastJsonResponseBodyDecodeConverter<Type>?{
        return null
    }
    companion object{
        var context:Context?=null
        var myApplication: MyApplication? = null
        var canTrustAll = false//是否开启证书验证
        @JvmStatic
        fun getInstance(): MyApplication? {
            if (myApplication == null) {
                myApplication = MyApplication()
            }
            return myApplication
        }
    }
}